package com.scs.application.modules.upms.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exceptions.BusinessException;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.upms.entity.User;
import com.scs.application.modules.upms.entity.UserWx;
import com.scs.application.modules.upms.mapper.UserMapper;
import com.scs.application.modules.upms.mapper.UserWxMapper;
import com.scs.application.modules.upms.service.UserWxService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description：微信用户绑定关系
 * @Date 2024-04-04
 */
@Slf4j
@AllArgsConstructor
@Service
public class UserWxServiceImpl extends BaseServiceImpl<UserWxMapper, UserWx> implements UserWxService, ApplicationRunner {

    @Resource
    private UserMapper userMapper;

    @Override
    public void bind(String loginKey, String openId) {
        loginKey = loginKey.toUpperCase();
        UserWx userWx = this.getOne(Wrappers.<UserWx>query().eq("login_key", loginKey).eq("open_id", openId), false);
        if (userWx != null) {
            return;
        }
        userWx = new UserWx();
        userWx.setLoginKey(loginKey).setOpenId(openId);
        this.save(userWx);
    }

    @Override
    public void unbind(String loginKey, String openId) {
        loginKey = loginKey.toUpperCase();
        this.remove(Wrappers.<UserWx>query().eq("login_key", loginKey).eq("open_id", openId));
    }

    @Override
    public List<User> getUserByOpenIdOrLoginKey(String openId,String loginKey) {
        loginKey = loginKey.toUpperCase();
        List<UserWx> userWxList = this.list(Wrappers.<UserWx>query().eq(StringUtils.isNotBlank(openId),"open_id", openId).eq(StringUtils.isNotBlank(loginKey),"login_key", loginKey));
        if (ObjectUtil.length(userWxList) == 0) {
            return null;
        }

        List<User> userList = userMapper.selectList(Wrappers.<User>query().in("login_key",userWxList.stream().map(UserWx::getLoginKey).collect(Collectors.toList())));
        if (userList != null && userList.size() > 0) {
            Map<String,UserWx> mapByLoginKey = userWxList.stream().collect(Collectors.toMap(UserWx::getLoginKey, item -> item));
            userList.forEach(user -> {
                String loginKeyUp = user.getLoginKey().toUpperCase();
                if (
                        mapByLoginKey.containsKey(loginKeyUp)
                                && mapByLoginKey.get(loginKeyUp).getFlagDefault() != null
                                && mapByLoginKey.get(loginKeyUp).getFlagDefault()
                ) {
                    user.setFlagDefaultVxLogin(true);
                }else{
                    user.setFlagDefaultVxLogin(false);
                }
            });
        }

        return userList;
    }

    @Override
    public List<String> getOpenIdByLoginKey(String loginKey) {
        loginKey = loginKey.toUpperCase();
        List<UserWx> userWxList = this.list(Wrappers.<UserWx>query().eq("login_key", loginKey));
        if (ObjectUtil.length(userWxList) == 0) {
            return null;
        }
        return userWxList.stream().map(UserWx::getOpenId).collect(Collectors.toList());
    }

    //设置默认登录账号
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefaultLogin(UserWx dto) {
        dto.setLoginKey(dto.getLoginKey().toUpperCase());
        synchronized (dto.getOpenId().intern()){
            List<UserWx> userWxList = this.list(Wrappers.<UserWx>query().eq("open_id", dto.getOpenId()));
            BusinessException.throwErrorIf(ObjectUtil.length(userWxList) ==0, "用户配置已发生变化，请刷新界面重试");
            if (!userWxList.stream().filter(item -> item.getLoginKey().equals(dto.getLoginKey())).findFirst().isPresent()) {
                BusinessException.throwError( "用户配置已发生变化，请刷新界面重试");
            }
            userWxList.stream().forEach(item -> {
                if (item.getLoginKey().equals(dto.getLoginKey())) {
                    item.setFlagDefault(true);
                }else{
                    item.setFlagDefault(false);
                }
            });
            this.updateBatchById(userWxList);
        }
    }

    @Override
    public void run(ApplicationArguments args){
        this.update(Wrappers.<UserWx>update().setSql("login_key = upper(login_key)"));
    }
}

